import { http } from "@/utils/http";
import type { ApiResponse } from "../../user";

const SPOTCHECK_BASE = "/seller/verify/stock";

export interface SpotCheckListItem {
  id: number;
  verify_code: string;
  status: number;
  buyer_amount: number;
  seller_amount: number;
  buyer_remark?: string;
  buyer_verify_create?: string | null;
  seller_verify_create?: string | null;
  product?: Record<string, any>;
  [key: string]: any;
}

export interface SpotCheckDetail {
  buyer_amount: number;
  verify_code: string;
  buyer_remark: string;
  seller_remark: string;
  seller_remark_media: {
    img: string[];
    video: string[];
  };
  seller_amount: number;
  product: Record<string, any>;
}

export interface SpotCheckListResponse {
  list: Array<SpotCheckListItem>;
  pagination: {
    total: number;
    page: number;
    page_size: number;
    current_page?: number;
    currentPage?: number;
    pageSize?: number;
  };
}

export type SpotCheckListResult = ApiResponse<SpotCheckListResponse>;
export type SpotCheckDetailResult = ApiResponse<SpotCheckDetail>;

const normaliseMediaPayload = (media: any) => {
  if (!media) return undefined;
  if (typeof media !== "object") return media;
  return {
    img: Array.isArray(media.img) ? media.img : [],
    video: Array.isArray(media.video) ? media.video : []
  };
};

const spotcheckApi = {
  fetch(params: Record<string, any>) {
    return http.request<SpotCheckListResult>("get", SPOTCHECK_BASE, {
      params
    });
  },

  read(id: number | string) {
    return http.request<SpotCheckDetailResult>(
      "get",
      `${SPOTCHECK_BASE}/${id}`
    );
  },

  update(id: number | string, payload: Record<string, any>) {
    const data = {
      ...payload,
      seller_remark_media: normaliseMediaPayload(payload.seller_remark_media)
    };

    return http.request<ApiResponse<SpotCheckDetail>>(
      "put",
      `${SPOTCHECK_BASE}/${id}`,
      {
        data
      }
    );
  }
};

export default spotcheckApi;
